import React from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text, ImageBackground,
    DeviceEventEmitter, Image, TouchableWithoutFeedback, TouchableOpacity, RefreshControl,
} from 'react-native';
import {inject, observer} from 'mobx-react';
import colors from '../../utils/colors';
import screen from '../../utils/screen';
import Images from '../../images/Images';
import Constants from '../../utils/Constants';
import {AppModal} from '../../widgets/modal';
import RequestUtil from '../../utils/RequestUtil';
import Api from '../../utils/Api';
import ShadowBoxView from '../../widgets/ShadowBoxView';
import {AppInfo, cutZero, FontFamily, getffly, numAdd, setTextThousand} from '../../utils/common';
import {OLBtn,LGBtn} from '../../widgets/buttons';
import AppEvent from '../../utils/AppEvent';
import LinearGradient from "react-native-linear-gradient";


@inject(['userStore'])
@observer
export default class Account extends React.Component{


    state={
        data:null,
        isRefreshing:false
    }


    componentDidMount() {

        this.listener = DeviceEventEmitter.addListener(AppEvent.update_account,()=>{
            this.getData()
        })

        this.getData()
    }

    componentWillUnmount() {
        this.listener && this.listener.remove()
    }

    getData(){

        AppModal.showLoading();
        this.setState({isRefreshing:true})
        RequestUtil.get(Api.account).then(res=>{

            let data = res.data
            console.log('account',data)
            this.setState({
                data:data,
                isRefreshing:false
            })

            this.props.userStore.setUser(null,{
                balance:data.user.balance,
                nickName:data.user.nickName,
                id:data.user.id
            })

            AppModal.hideTip()
        },error=>{
            this.setState({isRefreshing:false})
            AppModal.hideTip()
            console.log('vip error',error)
        })

    }

    getWithdraw = (goSet = false)=>{

        AppModal.showLoading();

        RequestUtil.get(Api.withdrawSet).then(res=>{

            let data = res.data
            console.log('提现',data)
            AppModal.hideTip()
            if(goSet){
                this.props.navigation.push('WithdrawSet',{withdrawal:data})
            }


        },error=>{
            AppModal.hideTip()
            if(error.code === -111){
                AppModal.showError(error.msg)
            }else{
                AppModal.showError(error.msg)
            }
            console.log('widthdraw error',error)
        })

    }

    withdrawCheck = ()=>{

        AppModal.showLoading();

        RequestUtil.get(Api.withdrawCheck).then(res=>{

            let data = res.data
            console.log('withdraw Check',data)
            AppModal.hideTip()
            this.props.navigation.push('Withdraw')


        },error=>{
            AppModal.hideTip()
            if(error.code === -8){
                this.showWithdrawDialog()
            }else{
                AppModal.showError(error.msg)

            }
            console.log('widthdraw error',error)
        })

    }



    showWithdrawDialog = ()=>{

        AppModal.alert(Constants.account.withdraw,Constants.account.withdraw_no_found,[
            {
                title: Constants.common.continue,
                onPress:()=>{
                    AppModal.hideAlert()
                    this.getWithdraw(true)
                }
            },{
                title: Constants.common.later,
                onPress:()=>{
                    AppModal.hideAlert()
                }
            },
        ])
    }

    renderHeader(){

        const {data} = this.state
        if(!data) return  null
        const {nickName,id,level} = data.user

        let nameStr = nickName;
        if(nickName.length > 10) {
            nameStr = nickName.substring(0,10) + "...";
        }

        return (
            <View style={styles.header}>
                <View>
                    <View style={{flexDirection: 'row',alignItems:'center'}}>
                        <Text style={ {color:'#000',fontSize:16,fontWeight:'bold'}}>{nameStr}</Text>
                        <Image source={Images.vip_icon}
                               resizeMode={'contain'}
                               style={{width:screen.PIXEL_30,height:screen.PIXEL_40,marginHorizontal:screen.PIXEL_10}}
                        />
                        <Text style={{fontSize: 16,color:'#000'}}>Lv.{level.name}</Text>
                    </View>
                    <Text style={{color:'#000',fontSize:13}}>ID {id}</Text>

                </View>
                <TouchableWithoutFeedback
                    onPress={()=>{
                        this.props.navigation.navigate('ChangeName')
                    }}
                >
                    <Image source={Images.edit} style={{width:screen.PIXEL_40,height:screen.PIXEL_40}}/>
                </TouchableWithoutFeedback>
            </View>
        )
    }


    renderItem = (title,subtitle)=>{
        return (
            <View style={{alignItems:'center',marginTop:screen.PIXEL_20}}>
                <Text style={{color:'#000',fontSize:14}}>{title}</Text>
                <Text style={{color:'#FF7B14',fontSize:14,fontWeight:getffly(FontFamily.medium)}}>{subtitle}</Text>
            </View>
        )
    }

    renderBalance(){
        const {user,taskOrder,taskReward,referralAndTeam} = this.state.data
        return (
            <ShadowBoxView

                shadowOption={{
                    radius:screen.PIXEL_40,
                    color:'#000',
                    x:0,
                    y:0,
                    border:5
                }}
            >
                <View style={{padding:screen.PIXEL_20,backgroundColor:'#fff',borderRadius:screen.PIXEL_40}}>

                    <View style={{flexDirection: 'row',justifyContent: 'space-between'}}>
                        <Text style={{color:'#000',fontSize:13}}>{Constants.account.current_balance}</Text>
                        <Text style={{color:'#377C74',fontSize:15}}
                              onPress={this.withdrawCheck}
                        >{Constants.account.withdraw}</Text>
                    </View>
                    <Text style={{color:'#FF7012',fontWeight:'bold',fontSize:50}}>{setTextThousand(cutZero("" + user.balance))}</Text>

                    <View style={{flexDirection: 'row',justifyContent: 'flex-end'}}>
                        <LGBtn
                            style={{flex:1,marginRight:screen.PIXEL_20,height:screen.PIXEL_80}}
                            title={Constants.account.recharge}
                            onPress={()=>{
                                this.props.navigation.navigate('Recharge')
                            }}
                        />
                        <OLBtn
                            style={{width:screen.scaleSize(193),height:screen.PIXEL_80}}
                            title={Constants.account.history}
                            onPress={()=>{
                                this.props.navigation.navigate('History')
                            }}
                        />

                    </View>

                    <View style={{height:1,backgroundColor:'rgba(32,32,32,0.3)',marginTop:screen.PIXEL_20}}/>

                    <View style={{width:'100%',flexDirection: 'row'}}>
                        <View style={{flex:1,alignItems:'center'}}>
                            {this.renderItem(Constants.account.today_order,taskOrder.count)}
                            {this.renderItem(Constants.account.today_reward,`${Constants.appsymbol} ${referralAndTeam.today}`)}
                            {this.renderItem(Constants.account.total_commission,`${Constants.appsymbol} ${taskReward.total}`)}
                        </View>

                        <View style={{flex:1}}>
                            {this.renderItem(Constants.account.today_commission,`${Constants.appsymbol} ${taskReward.today}`)}
                            {this.renderItem(Constants.account.order_amount,`${Constants.appsymbol} ${taskOrder.deposit}`)}
                            {this.renderItem(Constants.account.total_reward,`${Constants.appsymbol} ${referralAndTeam.total}`)}
                        </View>

                    </View>
                </View>

            </ShadowBoxView>
        )
    }

    renderInvest(){
        const {investment} = this.state.data.user
        let isInvest = false
        if(investment.totalAmount && investment.dailyProfit){
            isInvest = true
        }
        const contentW = screen.width - screen.PIXEL_80

        return  (
            <ShadowBoxView
                shadowOption={{
                    radius:screen.PIXEL_40,
                    color:'#000',
                    x:0,
                    y:0,
                    border:5
                }}
            >
                <View style={{width:contentW,flexDirection: 'row',backgroundColor:'#fff',
                    padding:screen.PIXEL_20,borderRadius:screen.PIXEL_40,height:screen.scaleSize(320)
                }}>

                    <Image source={Images.account_invest}
                           resizeMode={'contain'}
                           style={{width:screen.scaleSize(215),height:screen.scaleSize(142),position:'absolute',left:screen.PIXEL_20,
                               bottom:screen.PIXEL_30
                           }}
                    />
                    <View style={{position:'absolute',alignItems:'flex-end',right:screen.PIXEL_60,top:screen.PIXEL_30,left:0}}>
                        <Text style={{fontSize:18,color:'#000',fontWeight:'bold',marginTop:screen.PIXEL_30}}>{Constants.account.merchant_investment}</Text>
                        {
                            isInvest ? (
                                <View style={{flexDirection: 'row'}}>
                                    <View style={{alignItems:'flex-end'}}>
                                        <Text style={{fontSize:12,color:'#343235'}}>{Constants.account.current_investment}</Text>
                                        <Text style={{fontSize:11,color:'#297BFF'}}>{Constants.appsymbol}
                                            <Text style={{fontSize:18,fontWeight:'bold'}}>{investment.totalAmount}</Text>
                                        </Text>
                                    </View>

                                    <View style={{marginLeft:screen.PIXEL_20,alignItems:'flex-end'}}>
                                        <Text style={{fontSize:12,color:'#343235'}}>{Constants.account.daily_profit}</Text>
                                        <Text style={{fontSize:11,color:'#297BFF'}}>{Constants.appsymbol}
                                            <Text style={{fontSize:18,fontWeight:'bold'}}> {investment.dailyProfit}</Text>
                                        </Text>
                                    </View>

                                </View>
                            ): (
                                <Text style={{fontSize:11,color:'#343235',textAlign:'right'}}>{Constants.account.monthly_invite}</Text>
                            )
                        }




                        <TouchableOpacity
                            activeOpacity={0.8}
                            style={{marginTop:screen.PIXEL_20}}
                            onPress={() => {
                                this.props.navigation.navigate("Money");
                            }} >
                            <LinearGradient colors={['#408EFF', '#0062FF']} start={{ x: 0, y: 1 }} end={{ x: 1, y: 0 }} locations={[0, 1]}
                                            style={{ width: screen.PIXEL_230 , height: screen.PIXEL_80, justifyContent: 'center', alignItems: 'center', borderRadius: screen.PIXEL_40 }}>
                                <Text style={{ textAlign: 'center', fontFamily:getffly("bold"), fontSize: 16, color: '#FFFFFF'}}>{Constants.account.details}</Text>
                            </LinearGradient>
                        </TouchableOpacity >
                    </View>

                    <View style={{position:'absolute',top:3,right:screen.PIXEL_20}}>
                        <Text style={{fontSize:12,color:'#377C74'}}>{`${Constants.account.monthly_interest} ${investment.rate}`}</Text>
                    </View>


                </View>
            </ShadowBoxView>
        )

    }


    renderMenuItem(title,icon,onPress){
        return (
            <TouchableWithoutFeedback
                onPress={onPress}
            >
                <View style={{alignItems:'center'}}>

                    <Image source={icon}
                            resizeMode={'contain'}
                           style={{width:screen.PIXEL_60,height:screen.PIXEL_60}}
                    />

                    <Text style={{color:'#377C74',fontSize:15,marginTop:screen.PIXEL_10}}>{title}</Text>

                </View>
            </TouchableWithoutFeedback>
        )
    }

    renderMenu(){

        return (
            <ShadowBoxView

                shadowOption={{
                    radius:screen.PIXEL_40,
                    color:'#000',
                    x:0,
                    y:0,
                    border:5
                }}
            >
                <View style={{padding:screen.PIXEL_30,flexDirection: 'row',justifyContent: 'space-between',
                    backgroundColor:'#fff',borderRadius:screen.PIXEL_40
                }}>
                    {this.renderMenuItem(Constants.account.service,Images.message,()=>{
                        if(AppInfo.helpdata){
                            if(AppInfo.helpdata.disable){
                                AppModal.showTip('Function disabled')
                            }else{
                                AppModal.showHelp()
                            }
                        }
                    })}
                    {this.renderMenuItem(Constants.account.guide,Images.bookmark,()=>{
                        this.props.navigation.navigate('Guide')
                    })}
                    {this.renderMenuItem(Constants.account.setting,Images.setting,()=>{
                        this.props.navigation.navigate('Setting')
                    })}
                </View>
            </ShadowBoxView>
        )
    }

    render(){
        const {data,isRefreshing} = this.state
        return (
            <View style={styles.container}>

                <View style={styles.content}>

                    {this.renderHeader()}
                    {
                        data && (
                            <ScrollView
                                style={{flex: 1, marginBottom: 10}}
                                contentContainerStyle={{
                                    paddingVertical: screen.PIXEL_20,
                                    paddingHorizontal: screen.PIXEL_40,
                                }}
                                refreshControl = {
                                    <RefreshControl
                                        refreshing={ isRefreshing }
                                        onRefresh = {() => {
                                            this.getData()
                                        }}
                                    />
                                }
                            >
                                {this.renderBalance()}

                                <View style={{height:screen.PIXEL_30}}/>
                                {this.renderInvest()}
                                <View style={{height:screen.PIXEL_30}}/>
                                {this.renderMenu()}

                            </ScrollView>
                        )
                    }
                </View>


            </View>
        )
    }
}




const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:colors.tabBgColor
    },
    content:{
        flex:1,backgroundColor: '#fff',
        borderBottomLeftRadius:screen.PIXEL_110,
        borderBottomRightRadius:screen.PIXEL_110,
        paddingTop:screen.statusBarHeight
    },
    header:{
        flexDirection:'row',
        justifyContent:'space-between',
        paddingHorizontal:screen.PIXEL_60,
        marginVertical:screen.PIXEL_10
    },
})
